Skip to main content

C# : ASP.NET MVC Development: CRUD Operations, Paging, Sorting, and Searching

 

ASP.NET MVC is a powerful framework for building web applications, providing developers with tools for creating full-stack solutions. In this comprehensive guide, we'll cover the implementation of CRUD operations (Create, Read, Update, Delete), paging, sorting, and searching in an ASP.NET MVC application. We'll walk through each step with detailed explanations and provide code snippets to ensure a clear understanding.

Step 1: Setting Up the ASP.NET MVC Application: Begin by creating a new ASP.NET MVC project in Visual Studio. Choose the appropriate template and configure the project settings as needed.

Step 2: Creating the Model: Define the model that represents the data entity for which you want to perform CRUD operations. For example, let's create a Product model with properties such as Id, Name, Price, etc.

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
Step 3: Implementing CRUD Operations: Create controller actions to handle CRUD operations for the Product model. These actions will interact with the data repository to perform database operations.
public class ProductController : Controller
{
    private readonly IProductRepository _productRepository;

    public ProductController(IProductRepository productRepository)
    {
        _productRepository = productRepository;
    }

    // GET: /Product/Index
    public ActionResult Index()
    {
        var products = _productRepository.GetAll();
        return View(products);
    }

    // GET: /Product/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: /Product/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Product product)
    {
        if (ModelState.IsValid)
        {
            _productRepository.Add(product);
            return RedirectToAction("Index");
        }
        return View(product);
    }

    // GET: /Product/Edit/1
    public ActionResult Edit(int id)
    {
        var product = _productRepository.GetById(id);
        return View(product);
    }

    // POST: /Product/Edit/1
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Product product)
    {
        if (ModelState.IsValid)
        {
            _productRepository.Update(product);
            return RedirectToAction("Index");
        }
        return View(product);
    }

    // GET: /Product/Delete/1
    public ActionResult Delete(int id)
    {
        var product = _productRepository.GetById(id);
        return View(product);
    }

    // POST: /Product/Delete/1
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        _productRepository.Delete(id);
        return RedirectToAction("Index");
    }
}

Step 4: Implementing Paging, Sorting, and Searching: To implement paging, sorting, and searching functionality, you can use features provided by ASP.NET MVC or third-party libraries like DataTables or PagedList.

  • Paging: Implement paging by dividing the data into smaller chunks and displaying them on different pages.
  • Sorting: Allow users to sort the data based on specific columns.
  • Searching: Provide a search functionality to filter data based on user-defined criteria.
  • Step 5: Integrating with Views: Create views to render the user interface for each controller action. Ensure that the views include elements for displaying data, performing CRUD operations, and implementing paging, sorting, and searching features.

  • let's add paging, sorting, and searching functionality to our ASP.NET MVC application. We'll provide code snippets for each feature.

    Step 1: Implement Paging: You can use the PagedList.Mvc library to implement paging in your ASP.NET MVC application. First, install the library via NuGet:

Install-Package PagedList.Mvc
Then, in your controller action where you retrieve data, use the ToPagedList method to paginate the results:
public ActionResult Index(int? page)
{
    var pageNumber = page ?? 1;
    var pageSize = 10; // Number of items per page

    var products = _productRepository.GetAll().ToPagedList(pageNumber, pageSize);
    return View(products);
}
In your view, render the paging links using the PagedListPager HTML helper:
@using PagedList.Mvc
@model IPagedList<Product>

@{
    ViewBag.Title = "Product List";
}

<!-- Display Product List Here -->

@Html.PagedListPager(Model, page => Url.Action("Index", new { page }), PagedListRenderOptions.ClassicPlusFirstAndLast)
Step 2: Implement Sorting: You can implement sorting by allowing users to click on column headers to sort the data. Modify your controller action to handle sorting parameters:
public ActionResult Index(int? page, string sortOrder)
{
    ViewBag.NameSortParam = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
    ViewBag.PriceSortParam = sortOrder == "Price" ? "price_desc" : "Price";

    var products = _productRepository.GetAll();

    switch (sortOrder)
    {
        case "name_desc":
            products = products.OrderByDescending(p => p.Name);
            break;
        case "Price":
            products = products.OrderBy(p => p.Price);
            break;
        case "price_desc":
            products = products.OrderByDescending(p => p.Price);
            break;
        default:
            products = products.OrderBy(p => p.Name);
            break;
    }

    var pageNumber = page ?? 1;
    var pageSize = 10; // Number of items per page

    var sortedProducts = products.ToPagedList(pageNumber, pageSize);
    return View(sortedProducts);
}
In your view, add sorting links to column headers:
<th>
    @Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParam })
</th>
<th>
    @Html.ActionLink("Price", "Index", new { sortOrder = ViewBag.PriceSortParam })
</th>

Step 3: Implement Searching: You can implement searching by adding a search form to your view and modifying your controller action to filter results based on search criteria.

In your controller:

public ActionResult Index(int? page, string searchString)
{
    var products = _productRepository.GetAll();

    if (!String.IsNullOrEmpty(searchString))
    {
        products = products.Where(p => p.Name.Contains(searchString));
    }

    // Sorting logic here...

    var pageNumber = page ?? 1;
    var pageSize = 10; // Number of items per page

    var searchedProducts = products.ToPagedList(pageNumber, pageSize);
    return View(searchedProducts);
}
In your view, add a search form:
@using (Html.BeginForm("Index", "Product", FormMethod.Get))
{
    <p>
        Search by Name: @Html.TextBox("searchString")
        <input type="submit" value="Search" />
    </p>
}
Conclusion: By following the steps outlined in this guide, you can develop a robust ASP.NET MVC application that performs CRUD operations and includes features such as paging, sorting, and searching. ASP.NET MVC provides powerful tools and libraries to streamline the development process and create efficient and user-friendly web applications.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...